package com.mc.fastkit.ext

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.view.Gravity
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.core.graphics.drawable.RoundedBitmapDrawable
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import androidx.core.graphics.drawable.toBitmap

fun ImageView.toRounded(gravity: Int = Gravity.CENTER) {
    val curDrawable = drawable
    require(curDrawable != null) { "must be set src first" }
    if (curDrawable is RoundedBitmapDrawable) {
        curDrawable.isCircular = true
        curDrawable.gravity = gravity
    } else {
        setRoundedImage(curDrawable)
    }
}

fun ImageView.setRoundedImage(radius: Float) {
    val curDrawable = drawable
    require(curDrawable != null) { "must be set src first" }
    if (curDrawable is RoundedBitmapDrawable) {
        curDrawable.cornerRadius = radius
    } else {
        setRoundedImage(curDrawable, radius)
    }
}

fun ImageView.setRoundedImage(@DrawableRes drawable: Int) {
    setRoundedImage(BitmapFactory.decodeResource(resources, drawable))
}

fun ImageView.setRoundedImage(filePath: String) {
    setRoundedImage(BitmapFactory.decodeFile(filePath))
}

fun ImageView.setRoundedImage(drawable: Drawable?) {
    if (drawable == null) {
        setImageDrawable(null)
        return
    }
    setRoundedImage(drawable.toBitmap())
}

fun ImageView.setRoundedImage(bitmap: Bitmap?) {
    if (bitmap == null) {
        setImageBitmap(null)
        return
    }
    val roundedBitmap = RoundedBitmapDrawableFactory.create(resources, bitmap)
    roundedBitmap.isCircular = true
    setImageDrawable(roundedBitmap)
}

fun ImageView.setRoundedImage(@DrawableRes drawable: Int, radius: Float) {
    setRoundedImage(BitmapFactory.decodeResource(resources, drawable), radius)
}

fun ImageView.setRoundedImage(filePath: String, radius: Float) {
    setRoundedImage(BitmapFactory.decodeFile(filePath), radius)
}

fun ImageView.setRoundedImage(drawable: Drawable, radius: Float) {
    setRoundedImage(drawable.toBitmap(), radius)
}

fun ImageView.setRoundedImage(bitmap: Bitmap, radius: Float) {
    val roundedBitmap = RoundedBitmapDrawableFactory.create(resources, bitmap)
    roundedBitmap.cornerRadius = radius
    setImageDrawable(roundedBitmap)
}